import axios from 'axios';

// 1. 初始状态.
const state = () => ({
    envs: {},
    currentKey: {},
});

// 2. 计算属性.
const getters = {
    getConfigItems: (state) => () => state.envs[state.currentKey],
};

// 3. 异步修改.
const actions = {
    loadEnvs({ state }, iid) {
        axios.get(`/env/${iid}`).then((res) => {
            const envs = {};

            res.data.propertySources.forEach((item) => {
                if (item.name.startsWith('Config resource')) {
                    return;
                }

                envs[item.name] = Object.entries(item.properties).map((val) => ({
                    name: val[0],
                    value: val[1].value,
                }));
            });
            state.envs = envs;
            state.currentKey = res.data.propertySources[0].name;
        });
    },
};

// 4. 同步修改.
const mutations = {
    changeKey(state, key) {
        state.currentKey = key;
    },
};

// 5. 模块导出.
export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
};
